<?php

namespace app\system\controller;

use think\Db;
use think\Exception;
use app\system\model\ConfigModel;
use think\Request;

class Config extends Common
{

    protected $table = 'config', $table_images = 'test_images', $name = '示例';

    private function select()
    {
        $where = ['t.is_del' => '0'];
        $list = db($this->table . ' t')->where($where)->order('t.create_time desc');

        return $list;
    }

    function index()
    {


        $list = $this->select()->paginate(20, false, ['query' => request()->get()]);

        $this->assign('list', $list);
        return $this->fetch();
    }

    function info($id)
    {
        $info = db($this->table . ' t')
            ->join('area a1', 'a1.id=t.province', 'left')
            ->join('area a2', 'a2.id=t.city', 'left')
            ->join('area a3', 'a3.id=t.county', 'left')
            ->field('t.*,a1.AreaName as province_name,a2.AreaName as city_name,a3.AreaName as county_name')
            ->where(['t.id' => $id])->find();
        $this->assign('info', $info);

        $images = db($this->table_images)->where(['upid' => $id])->select();
        $this->assign('images', $images);

        return $this->fetch();
    }

    function add($id = '')

    {
        if ($id) {
            //数据
            $info = db($this->table)->find($id);
            // $images = db($this->table_images)->where(['upid' => $id])->order('id asc')->select();
            // $this->assign('images', $images);
        } else {
            //默认数据
            $info = ['radio' => '0'];
        }

        $arr = array(
            'year_1' => '年选择器',
            'month_1' => '年月选择器',
            'time_1' => '时间选择器',
            'datetime_1' => '日期时间选择器',
            'year_2' => '年范围',
            'month_2' => '年月范围',
            'time_2' => '时间范围',
            'datetime_2' => '日期时间范围'
        );
        $this->assign('layer_date', $arr);
        $this->assign('suffix', ['元', '天', '个', '%']);
        $this->assign('info', $info);
        return $this->fetch();
    }

    function save($id = '')
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {

                //数据
                $param = input('post.');
                $config = new ConfigModel();
                if ($id) {
                    $param['id'] = $id;
                    $flag = $config->editConfig($param);
                } else {
                    $flag = $config->insertConfig($param);
                }
                cache('db_config_data', null);
                action('common/Logs/addLog', ['管理员[' . $this->admin['AdminName'] . ']新增' . $param['title'] . '参数' . $this->name . '，' . $this->name . 'ID[' . $id . ']']);
                return return_message($flag['code'], $flag['msg']);
            } catch (Exception $e) {
                Db::rollback();
                return return_message('0', $e->getMessage(), '2');
            }
        } else {
            return return_message('0', '保存失败', '1');
        }
    }

    /**
     * @return mixed
     * 原点 2020年5月28日08:43:27 网站配置页面
     */
    public function group()
    {

        $id = input('id', 1);
        $config = new ConfigModel();
        $list = $config->getAllConfig(array('status' => 1, 'group' => $id, 'is_del' => 0));
        if ($list) {
            $this->assign('list', $list);
        }
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * @param $config -- 提交的参数
     * @return array
     * 原点 2020年5月27日17:43:41 保存相关配置
     */
    public function save_group($config)
    {


        try {
            if ($config && is_array($config)) {
                $Config = Db::name('Config');
                foreach ($config as $name => $value) {
                    $map = array('name' => $name);

                    $info = $Config->where($map)->field('title,type,format,suffix')->find();
                    if ($info['suffix'] == '%') {
                        $value = $value / 100;
                    }
                    switch ($info['type']) {
                        case 7:
                            $value = set_layDate($value, $info['format']);
                            if($value == false){
                                return json(['code' => 0, 'message' => $info['title'] . '错误']);
                            }
                            break;
                        case 9:
                            $start = $value;
                            $end = $config[$name . '_2'];
                            if ($info['suffix'] == '%') {
                                $end = $end / 100;
                            }
                            //区间格式目前只支持数字
                            if ($end < $start) {
                                return json(['code' => 0, 'message' => $info['title'] . '错误']);
                            }
                            $value = $start . ',' . $end;
                            unset($config[$name . '_2']);
                            break;
                    }

                    $Config->where($map)->setField('value', $value);
                }
            }
            cache('db_config_data', null);
            return return_message('1', '保存成功');
        } catch (\Exception $e) {
            return return_message('0', $e->getMessage());
        }

    }


    /**
     * @param $id -- ID
     * @param $key -- 要更改的key
     * @param $val -- 更改的值
     * @return array
     * 更改状态
     */
    function state($id, $key, $val)
    {
        return $this->editState($this->table, $id, $key, $val);
    }


    /**
     * @return \think\response\Json
     * 原点 2020年5月30日11:47:19 清除缓存
     */
    public function clear_cache()
    {
        if (delete_dir_file(CACHE_PATH) || delete_dir_file(TEMP_PATH)) {
            return return_message('1', '清除缓存成功');
        } else {
            return return_message('0', '清除缓存失败');
        }
    }


}